package com.longge;

/**
 * @创建人 xinglongge
 * @创建时间 2021/7/14
 * @描述
 */
public class Solve {
    public void solve(char[][] board) {
        if (board.length == 0) return;
        int m = board.length;
        int n = board[0].length;
        int dummy = m * n;
        UF uf = new UF(dummy + 1);
        //首列和尾列相连
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') uf.union(i * n, dummy);
            if (board[i][n - 1] == 'O') uf.union(i * n + n - 1, dummy);
        }
        //首行和末行相连
        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O') uf.union(i, dummy);
            if (board[m - 1][i] == 'O') uf.union((m - 1) * n + i, dummy);
        }
        //定义方向数组
        int[][] d = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        //找到所有连通分量
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (board[i][j] == 'O') {
                    for (int k = 0; k < d.length; k++) {
                        int x = i + d[k][0];
                        int y = j + d[k][1];
                        if (board[x][y] == 'O') uf.union(x * n + y, i * n + j);
                    }
                }
            }
        }
        //如果'O'未连通 则需要被替换成'X'
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (board[i][j] == 'O' && !uf.connected(i * n + j, dummy)) {
                    board[i][j] = 'X';
                }
            }
        }

    }

    class UF {
        // 连通分量个数
        private int count;
        // 存储一棵树
        private int[] parent;
        // 记录树的“重量”
        private int[] size;

        public UF(int n) {
            this.count = n;
            parent = new int[n];
            size = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP == rootQ)
                return;

            // 小树接到大树下面，较平衡
            if (size[rootP] > size[rootQ]) {
                parent[rootQ] = rootP;
                size[rootP] += size[rootQ];
            } else {
                parent[rootP] = rootQ;
                size[rootQ] += size[rootP];
            }
            count--;
        }

        public boolean connected(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            return rootP == rootQ;
        }

        private int find(int x) {
            while (parent[x] != x) {
                // 进行路径压缩
                parent[x] = parent[parent[x]];
                x = parent[x];
            }
            return x;
        }
    }
}
